package comment_api

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/liu-cn/json-filter/filter"
	"giv-vue-blog/global"
	"giv-vue-blog/models"
	"giv-vue-blog/models/res"
	"giv-vue-blog/service/redis_ser"
	"gorm.io/gorm"
)

type CommentListRequest struct {
	ArticleID string `form:"article_id"`
}

// CommentListView 获取评论列表
// @Summary 获取评论列表
// @Tags 评论管理
// @Accept json
// @Produce json
// @Param article_id query string true "文章ID"
// @Success 200 {string} json "{"code": 0, "message": "请求成功", "data": []CommentModel}"
// @Failure 400 {string} json "{"code": 1, "message": "参数错误"}"
// @Failure 500 {string} json "{"code": 2, "message": "服务器内部错误"}"
// @Router /api/comments [get]
func (CommentApi) CommentListView(c *gin.Context) {
	var cr CommentListRequest
	err := c.ShouldBindQuery(&cr)
	if err != nil {
		res.FailedWithError(err, &cr, c)
		return
	}
	RootCommentList := FindArticleCommentList(cr.ArticleID)
	//filter.Omit("comment", RootCommentList) 中的第一个参数comment要与结构体中设置的omit(参数)相同
	//通过filter.Omit与omit()将返回结果中不想要的字段给隐藏掉  Select是展示选择的字段
	res.OkWithData(filter.Select("comment", RootCommentList), c)
	return
}

// FindArticleCommentList 查找文章的评论列表
func FindArticleCommentList(articleId string) (RootCommentList []*models.CommentModel) {
	global.DB.Preload("User").Find(&RootCommentList, "article_id=? and parent_comment_id is null", articleId)
	diggInfo := redis_ser.NewCommentDigg().GetInfo()
	//遍历评论,递归查根评论下的所有子评论
	for _, model := range RootCommentList {
		var subCommentList, newCommentList []models.CommentModel
		FindSubComment(*model, &subCommentList)
		for _, commentModel := range subCommentList {
			digg := diggInfo[fmt.Sprintf("%d", commentModel.ID)]
			commentModel.DiggCount = commentModel.DiggCount + digg
			newCommentList = append(newCommentList, commentModel)
		}
		modelDigg := diggInfo[fmt.Sprintf("%d", model.ID)]
		model.DiggCount = model.DiggCount + modelDigg
		model.SubComments = newCommentList
	}
	return
}

// FindSubComment 递归查评论下的子评论
func FindSubComment(model models.CommentModel, subCommentList *[]models.CommentModel) {
	err := global.DB.Preload("SubComments.User").Take(&model).Error //SubComments.User 拿到这个子评论对应的用户信息
	if err == gorm.ErrRecordNotFound {
		//没找到
		return
	}
	for _, comment := range model.SubComments {
		*subCommentList = append(*subCommentList, comment)
		FindSubComment(comment, subCommentList)
	}
	return
}
func FindSubCommentCount(model models.CommentModel) (subCommentList []models.CommentModel) {
	FindSubCommentList(model, &subCommentList)
	return subCommentList
}
func FindSubCommentList(model models.CommentModel, subCommentList *[]models.CommentModel) {
	global.DB.Preload("SubComments").Take(&model) //SubComments.User 拿到这个子评论对应的用户信息
	for _, comment := range model.SubComments {
		*subCommentList = append(*subCommentList, comment)
		FindSubComment(comment, subCommentList)
	}
	return
}
